//
//  FSCMessageListViewModel.swift
//  FamiliesSchoolConnection
//
//  Created by 花花蔡 on 2016/12/29.
//  Copyright © 2016年 com.HuaHuaCai. All rights reserved.
//

import UIKit
import SVProgressHUD

//定义表示刷新类型的枚举
enum LoadType {
    case down
    case up
}


class FSCMessageListViewModel {
    
    //数据源数组,放消息模型对象
    var messageModelArr:[FSCMessageViewModel] = []
    
    
    //请求数据
    func loadData(refreshType:LoadType,finished:@escaping (_ isRefresh:Bool)->() ) -> Void {
        //获得接口
        let urlStr = "ZH-schoolname-S-getJXNotification"
        
        //参数
        //获得当前刷新的通知ID，下拉时直接给0，上拉时给最后一天通知的ID
        //先获得最后一条通知的ID
        let lastNot_id = messageModelArr.last?.message.not_id ?? 0
        let not_id = refreshType == .down ? 0:lastNot_id
        //刷新类型
        let load_type = refreshType == .down ? 1:2
        
        let parm = ["key":userID,"id":not_id,"load_type":load_type] as [String : Any]
        
        FSCNetworkTools.shared.request(url: urlStr, parameters: parm) { [weak self] (data, error) in
            guard let data = data as? NSDictionary else {
                SVProgressHUD.showInfo(withStatus: "网络异常")
                return
            }
            
            switch data["result"] as! Int {
            case 0:
                //获得消息数组
                guard let dictArr = data["data"] as? [[String:Any]] else {
                    return
                }
                //创建一个可变的数组保存模型视图
                var messageVMArr = [FSCMessageViewModel]()
                //循环转换数据
                for dict in dictArr {
                    let message = FSCMessageModel(dict: dict)
                    //获得回复列表字典数组
                    let rlDictArr = message.replaylist as! [[String:Any]]
                    //保存
                    var listModelArr = [FSCReplayListModel]()
                    for d in rlDictArr {
                        let rlListModel = FSCReplayListModel(dict: d)
                        listModelArr.append(rlListModel)
                    }
                    //将装换为模型的回复列表数组赋值给消息模型的属性
                    message.replaylist = listModelArr
                    messageVMArr.append(FSCMessageViewModel(model: message))
                }
                //赋值给外部属性
                if refreshType == .down {
                    self?.messageModelArr = messageVMArr
                }else {
                    self?.messageModelArr += messageVMArr
                }
                //通知控制器刷新
                finished(true)
            case 1:
                //数据加载异常
                SVProgressHUD.showInfo(withStatus: "数据加载异常")
                finished(false)
            default:
                break
            }
        }
    }

    
    
}
